<?php

namespace app\system\controller\order;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use think\facade\Db;


class Customer extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'create_time,desc';

    protected array|string $preExcludeFields = [];

    protected string|array $quickSearchField = [];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\order\Customer();
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }


        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->with(['customer_info', 'detail'])
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items();

        foreach($list as $key => $val){
            $list[$key]['create_time'] = date('Y-m-d', $val['create_time']);
            $list[$key]['is_detail'] = count($val['detail']) > 0 ? true : false;
        }

        $this->success('', [
            'list'   => $list,
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }




    /**
     * 添加
     */
    public function add(): void
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(empty($data['customer_id'])) $this->error(__('请选择客户名'));
            if(empty($data['type'])) $this->error(__('请选择订单类型'));
            if(empty($data['create_time'])) $this->error(__('请选择下单时间'));


            $type = $data['type'];
            $data['type'] = $type[0];
            $data['trade_type'] = $type[1];
            $data['create_time'] = strtotime($data['create_time']);
            $data['out_trade_no'] = 'YN' . date('ymd', $data['create_time']);

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }


    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            if(empty($data['customer_id'])) $this->error(__('请选择客户名'));
            if(empty($data['type'])) $this->error(__('请选择订单类型'));
            if(empty($data['create_time'])) $this->error(__('请选择下单时间'));


            $type = $data['type'];
            $data['type'] = $type[0];
            $data['trade_type'] = $type[1];
            $data['create_time'] = strtotime($data['create_time']);
            $data['out_trade_no'] = 'YN' . date('ymd', $data['create_time']);


            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['create_time'] = date('Y-m-d', $row['create_time']);
        $row['type'] = [$row['type'], $row['trade_type']];

        $this->success('', [
            'row' => $row
        ]);
    }










}